﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Client_Server_Interface;

namespace BTM_Client_Application.SupportClasses
{
    public class MegaDeviceTree
    {
        public Style TreeViewItemStyle { get; set; }

        public DeviceTree DeviceTree { get; set; }

        public List<string> Regions { get; set; }

        public List<string> Blrs { get; set; }

        public List<StationElement> Stations { get; set; }

        public List<IDeviceInterface> Devices { get; set; } 
        
        //Привязывает информацию о станциях и устройствах к маркерам и элементам дерева
        public void SetStations(double zoom, double scaling)
        {
            var tree = DeviceTree;
            Regions = new List<string>(tree.DeviceTreeItems.Count);
            Stations = new List<StationElement>();
            Blrs = new List<string>();
            foreach (DeviceTreeItem region in tree.DeviceTreeItems)
            {
                foreach (DeviceTreeItem station in region.SubItems)
                {
                    var im = new Image();
                    var p = StationInfoControl.GetOnPopup(station.AdditionalInfo as DeviceTreeItem.StationInfo, im);
                    //Правой кнопкой по маркеру на карте показывать Popup
                    im.MouseRightButtonUp += (sender, args) =>
                        {
                            p.IsOpen = true;
                        };
                    im.Source = Res.ResizeImage(Res.MapIconName, (int)(128 * zoom / scaling), (int)(128 * zoom / scaling));
                    var treeItem = new TreeViewItem
                        {
                            //Header = SpecificTreeViewHeader.Create(DeviceTreeItem.ItemType.Station,
                            //                                       ((DeviceTreeItem.StationInfo) station.AdditionalInfo)
                            //                                           .Station),
                            Header = new MyTreeViewItemHeader(DeviceTreeItem.ItemType.Station,
                                                                   ((DeviceTreeItem.StationInfo) station.AdditionalInfo)
                                                                       .Station)
                        };
                    //Правой кнопкой по станции в дереве показывать Popup
                    treeItem.MouseRightButtonUp += (sender, args) =>
                        {
                            p.IsOpen = true;
                        };
                    treeItem.MouseDoubleClick += (sender, args) =>
                        {
                            //p.IsOpen = true;
                        };
                    Stations.Add(new StationElement
                        {
                            TreeItem = treeItem,
                            Info = (DeviceTreeItem.StationInfo) station.AdditionalInfo,
                            MapMarker = new MapMarker(im, station.Header),
                            StationPopup = p
                        });
                    if (station.AdditionalInfo as DeviceTreeItem.StationInfo != null)
                        if (!Blrs.Contains((station.AdditionalInfo as DeviceTreeItem.StationInfo).BLR))
                            Blrs.Add((station.AdditionalInfo as DeviceTreeItem.StationInfo).BLR);
                }
                Regions.Add(region.Header);
            }
        }

        /// <summary>
        /// Перед вызовом установить Devices!
        /// </summary>
        public void SetDevices()
        {
            var devList = Devices;
            foreach (var device in devList)
            {
                var stName = device.DevInfo.ParentInfo.Station;
                var st = Stations.Single(s => s.Info.Station == stName);
                st.Devices.Add(device);
                device.ErrorsListChanged += st.DeviceErrorsListChanged;
            }
        }

        public List<TreeViewItem> GetTreeViewItemsSource()
        {
            var treeItemsList = new List<TreeViewItem>();
            foreach (var region in DeviceTree.DeviceTreeItems)
            {
                var rh = new MyTreeViewItemHeader(region.TypeItem, region.Header);
                var regionItem =
                    new TreeViewItem
                    {
                        Header = rh,
                        ItemContainerStyle = TreeViewItemStyle,
                        Tag = new Dictionary<string, ErrorsState>()
                    };

                foreach (var station in region.SubItems)
                {
                    var st =
                        Stations.Single(s => s.Info.Station == station.Header.ToString(CultureInfo.InvariantCulture));
                    var stationItem = st.TreeItem;
                    stationItem.ItemContainerStyle = TreeViewItemStyle;

                    foreach (var device in st.Devices)
                    {
                        string header = !string.IsNullOrEmpty(device.DevInfo.Title) ? device.DevInfo.Title : device.DevInfo.Device;
                        var devHeader = new MyTreeViewItemHeader(DeviceTreeItem.ItemType.Device, header);
                        device.ErrorsListChanged += devHeader.OnDeviceErrorsListChanged;
                        var devItem = new TreeViewItem()
                            {
                                Header = devHeader,
                                ItemContainerStyle = TreeViewItemStyle,
                                Tag = DeviceInfoControl.GetControl(device),
                            };
                        devItem.ToolTip = DeviceInfoControl.GetOnToolTip(devItem.Tag as DeviceInfoControl);
                        stationItem.Items.Add(devItem);
                        
                        (stationItem.Items[0] as TreeViewItem).MouseRightButtonUp += (sender, args) =>
                            {
                                args.Handled = true;
                            };
                    }
                    regionItem.Items.Add(stationItem);
                }
                treeItemsList.Add(regionItem);
            }
            return treeItemsList;
        }
    }
}
